const api = require('../../utils/api.js');

// 灵感建议词库
const suggestionSource = {
  protagonists: ['小兔子', '勇敢的狮子', '机器猫', '小仙女', '一朵云', '好奇的恐龙'],
  partners: ['聪明的狐狸', '善良的大象', '会飞的鱼', '害羞的刺猬', '月亮婆婆'],
  events: ['寻找神秘的宝石', '举办一场派对', '学习飞翔', '去太空探险', '建造一座糖果屋']
};

Page({
  data: {
    // ... 原有数据
    storyContent: '欢迎来到AI故事乐园！\n请在下方输入故事元素，开始创作一个独一无二的睡前故事吧。',
    richStoryContent: [],
    protagonist: '',
    partner: '',
    event: '',
    typewriterTimer: null,
    currentFullStory: '',
    isFavorite: false,

    // --- 新增数据 ---
    suggestions: {
      protagonists: suggestionSource.protagonists,
      partners: suggestionSource.partners,
      events: suggestionSource.events
    },
    isGenerating: false // 控制生成按钮的加载状态
  },

  onLoad() {
    this.setData({ richStoryContent: [{ type: 'text', text: this.data.storyContent }] });
  },

  // --- 导航事件处理 ---
  navigateToGuoxue() { wx.navigateTo({ url: '/pages/guoxue/guoxue' }); },
  navigateToEnglish() { wx.navigateTo({ url: '/pages/english/english' }); },
  navigateToRiddle() { wx.navigateTo({ url: '/pages/riddle/riddle' }); },

  // --- 输入框事件处理 ---
  onProtagonistInput(e) { this.setData({ protagonist: e.detail.value }); },
  onPartnerInput(e) { this.setData({ partner: e.detail.value }); },
  onEventInput(e) { this.setData({ event: e.detail.value }); },

  // --- 新增：建议标签点击 ---
  onSuggestionTap(e) {
    const { field, value } = e.currentTarget.dataset;
    this.setData({ [field]: value });
  },

  // --- 新增：随机填充 ---
  randomizeInputs() {
    const { protagonists, partners, events } = suggestionSource;
    this.setData({
      protagonist: protagonists[Math.floor(Math.random() * protagonists.length)],
      partner: partners[Math.floor(Math.random() * partners.length)],
      event: events[Math.floor(Math.random() * events.length)]
    });
  },

  // --- 故事生成（已优化） ---
  generateStory() {
    if (this.data.isGenerating) return;

    if (!this.data.protagonist || !this.data.event) {
      wx.showToast({ title: '主角和事件不能为空哦', icon: 'none' });
      return;
    }

    this.setData({
      isGenerating: true, // 开始生成，按钮进入加载状态
      storyContent: '',
      richStoryContent: [],
      currentFullStory: '',
      isFavorite: false
    });

    if (this.data.typewriterTimer) {
      clearTimeout(this.data.typewriterTimer);
    }

    // 注意：api.js内部还有一个wx.showLoading，在真实项目中应统一管理
    api.generateStory(this.data.protagonist, this.data.partner, this.data.event)
      .then(story => {
        this.setData({ currentFullStory: story, isGenerating: false });
        this.typewriterEffect(story);
        this.checkFavoriteStatus(story);
      })
      .catch(error => {
        this.setData({ 
          isGenerating: false,
          storyContent: '生成失败了，请检查网络或稍后再试。 '
        });
        wx.showToast({ title: error || '生成失败，请稍后再试', icon: 'none' });
      });
  },

  // --- 效果和状态 ---
  typewriterEffect(fullText) {
    let i = 0;
    const type = () => {
      if (i < fullText.length) {
        this.setData({
          storyContent: fullText.substring(0, i + 1),
          richStoryContent: this.highlightKeywords(fullText.substring(0, i + 1))
        });
        i++;
        this.data.typewriterTimer = setTimeout(type, 100);
      } else {
        this.setData({ richStoryContent: this.highlightKeywords(fullText) });
      }
    };
    type();
  },

  highlightKeywords(text) {
    const keywords = [this.data.protagonist, this.data.partner, this.data.event].filter(Boolean);
    if (keywords.length === 0) return [{ type: 'text', text }];
    const regex = new RegExp(`(${keywords.join('|')})`, 'g');
    const parts = text.split(regex);
    return parts.map(part => {
      if (keywords.includes(part)) {
        return { type: 'text', text: part, attrs: { class: 'highlight' } };
      } else {
        return { type: 'text', text: part };
      }
    });
  },

  // --- 收藏功能 ---
  toggleFavorite() {
    // ... (收藏逻辑保持不变)
    const favorites = wx.getStorageSync('favorite_stories') || [];
    const { currentFullStory, isFavorite } = this.data;
    if (!currentFullStory) return;

    if (isFavorite) {
      const index = favorites.indexOf(currentFullStory);
      if (index > -1) {
        favorites.splice(index, 1);
        wx.setStorageSync('favorite_stories', favorites);
        this.setData({ isFavorite: false });
        wx.showToast({ title: '已取消收藏', icon: 'success' });
      }
    } else {
      favorites.unshift(currentFullStory);
      wx.setStorageSync('favorite_stories', favorites);
      this.setData({ isFavorite: true });
      wx.showToast({ title: '收藏成功', icon: 'success' });
    }
  },

  checkFavoriteStatus(story) {
    const favorites = wx.getStorageSync('favorite_stories') || [];
    this.setData({ isFavorite: favorites.includes(story) });
  }
});
